import { createUniqueId } from "solid-js"
import { VirtualListCore } from "./core";

export * from './core';

const CONTAINER_CLASSNAME = `cm-virtual-${createUniqueId()}`
let globalContainerStylesheet: HTMLStyleElement;

const insertGlobalStylesheet = () => {
    if (!globalContainerStylesheet) {
        globalContainerStylesheet = document.createElement('style')
        globalContainerStylesheet.type = 'text/css'

        globalContainerStylesheet.textContent = `
        .${CONTAINER_CLASSNAME} {
            position: relative !important;
            flex-shrink: 0 !important;
            width: 100%;
            height: 100%;
            overflow: auto;
        }
        .${CONTAINER_CLASSNAME} > * {
            width: 100%;
            will-change: transform !important;
            box-sizing: border-box !important;
            contain: strict !important;
            position: absolute !important;
            top: 0 !important;
            left: 0 !important;
        }
      `
        document.head.appendChild(globalContainerStylesheet)
    }
}

export interface VirtualListProps {
    height?: number,
    maxHeight?: number,
    itemEstimatedSize: number
    children: any,
    overscan?: number,
    items: any[]
}

export interface MeasuredData {
    size: number,
    offset: number,
}
export interface IMeasuredDataMap {
    [key: number]: MeasuredData
}

export function VirtualList(props: VirtualListProps) {
    insertGlobalStylesheet();

    const containerHeight = props.height ?? props.maxHeight;
    if (containerHeight === undefined) {
        console.error('Virtual List need height or maxHeight prop');
    }

    let scrollElement: any;
    let contentElement: any;
    let bodyElement: any;

    return <div class={CONTAINER_CLASSNAME} ref={scrollElement}>
        <div ref={contentElement}>
            <div ref={bodyElement}>
                <VirtualListCore scrollElement={scrollElement} contentElement={contentElement} bodyElement={bodyElement}
                {...props}/>
            </div>
        </div>
    </div>
}